import path from "path";
import json from "@rollup/plugin-json";
import resolvePlugin from "@rollup/plugin-node-resolve";
import ts from "rollup-plugin-typescript2";

const packagesDir = path.resolve( __dirname, "packages" );
const packageDir = path.resolve( packagesDir, process.env.TARGET ); // 找到要打包的某个包
const resolve = ( p ) => path.resolve( packageDir, p );
const pkg = require( resolve( "package.json" ) );
const name = path.basename( packageDir ); // 取文件名
// 配置映射
const outputConfig = {
  "esm-bundler": {
    // es
    file: resolve( `dist/${ name }.esm-bundler.js` ),
    format: "es",
  },
  cjs: {
    // node require
    file: resolve( `dist/${ name }.cjs.js` ),
    format: "cjs",
  },
  global: {
    // 直接页面引入
    file: resolve( `dist/${ name }.global.js` ),
    format: "iife",
  },
};

// 自己在package.json中定义的选项
const options = pkg.buildOptions;

function createConfig ( output ) {
  output.name = options.name;
  output.sourcemap = true; // 生成sourcemap
  return {
    input: resolve( `src/index.ts` ),
    output,
    plugins: [
      json(),
      ts( {
        // ts 插件
        tsconfig: path.resolve( __dirname, "tsconfig.json" ),
      } ),
      resolvePlugin(), // 解析第三方模块插件
    ],
  };
}
// rollup 最终需要到出配置
export default options.formats.map( ( format ) =>
  createConfig( outputConfig[ format ] )
);
